import { _decorator, CCInteger, Component, instantiate, Label, Node, ScrollView, Size, UITransform, Vec3 } from 'cc';
import { RankNormalItem } from '../pop/RankNormalItem';
const { ccclass, property } = _decorator;

@ccclass('ListView')
export class ListView extends ScrollView {
    @property(Node)
    mItem: Node = null;
    @property(Node)
    mNdContent: Node = null;
    @property({ type: CCInteger })
    mItemHeight = 60;  //Item的高度

    private maxCount = 6;
    private mData = null;
    private mNCur = 0;
    private mLine = 0;
    private mLtItem: Node[] = [];
    private mString = "";

    protected onLoad(): void {
        this.elastic = false;
    }

    InitListView<T>(data: any, alias: string) {
        this.mData = data;
        let transform = this.mNdContent.getComponent(UITransform);
        let size = new Size(transform.width, data.length * this.mItemHeight);
        this.mNdContent.getComponent(UITransform).setContentSize(size);
        this.mString = alias;
        for (let i = 0; i < this.maxCount; i++) {
            if (!this.mData[this.mNCur + i]) continue;
            let item = instantiate(this.mItem);
            let sc = item.getComponent(alias) as any;
            if (sc) sc.InitItem(this.mData[this.mNCur + i], i)
            this.mNdContent.addChild(item);
            item.position = new Vec3(0, (i + 1) * this.mItemHeight * -1 + this.mItemHeight / 2);
            this.mLtItem.push(item);
        }
    }

    OnScrollEvent() {
        let viewHight = this.mNdContent.parent.getComponent(UITransform).contentSize.height;
        this.mLine = viewHight / 2;
        this.mNCur = Math.floor((this.mNdContent.position.y - this.mLine) / this.mItemHeight);
        this.updateListView();
    }

    updateListView() {
        for (let i = 0; i < this.mLtItem.length; i++) {
            if (i + this.mNCur > this.mData.length - 1) continue;
            this.mLtItem[i].position = new Vec3(0, (this.mNCur + i + 1) * this.mItemHeight * -1 + this.mItemHeight / 2);
            let sc = this.mLtItem[i].getComponent(this.mString) as any;
            if (sc) sc.InitItem(this.mData[this.mNCur + i], this.mNCur + i)
        }
    }


    start() {

    }

    update(deltaTime: number) {

    }


}


